package znet

import (
	"fmt"
	"sync"
	zinterface "zinx/zInterface"
)

/*
	连接管理模块
*/

 type ConnManager struct{
	//管理的连接集合
	connections map[uint32]zinterface.IConnection
	//保护连接集合的读写锁
	connLock sync.RWMutex
 }

 //ConnManager的构造函数
 func NewConnManager()*ConnManager{
	return &ConnManager{
		connections: make(map[uint32]zinterface.IConnection),
	}
 }

 //添加连接
 func(cm *ConnManager)Add(conn zinterface.IConnection){
	//先加写锁进行保护，再操作map
	cm.connLock.Lock()
	defer cm.connLock.Unlock()
	// 添加连接
	cm.connections[conn.GetConnID()] = conn
	// 记录一下日志
	fmt.Printf("connection add connID = %d to ConnManager success,conn num = %d\n",
		conn.GetConnID(),cm.Len())
 }

 //删除连接
 func(cm *ConnManager)Remove(conn zinterface.IConnection){
	//先加写锁进行保护，再操作map
	cm.connLock.Lock()
	defer cm.connLock.Unlock()
	delete(cm.connections,conn.GetConnID())
	// 记录一下日志
	fmt.Printf("connections remove connID = %d from ConnManager success,conn num = %d\n",
		conn.GetConnID(),cm.Len())
 }

 //根据connID获得连接
 func(cm *ConnManager)Get(connID uint32)(zinterface.IConnection,error){
	//先加读锁进行保护，再操作map
	cm.connLock.RLock()
	defer cm.connLock.RUnlock()
	if conn,ok := cm.connections[connID];ok{
		return conn,nil
	}
	return nil,fmt.Errorf("connection NOT FOUND")
 }

 //获得当前的连接总数
 func(cm *ConnManager)Len()int{
	return len(cm.connections)
 }

 //清除并终止所有的连接
 func(cm *ConnManager)Clear(){
	//先加写锁进行保护，再操作map
	cm.connLock.Lock()
	defer cm.connLock.Unlock()
	//循环遍历，对每一条connection进行处理
	for connID, conn := range cm.connections {
		//停止每一条connection
		conn.Stop()

		//从map中将该connection删除掉
		delete(cm.connections,connID)
	}
	// 记录一下日志
	fmt.Printf("clear all connections success,conn num = %d\n",
		cm.Len())
 }